#!/bin/sh

REPODIR="/backups/tar-backups/"
SNARDIR="$REPODIR/snar"
DO_FULL_BACKUP="no"
case "$1" in
    --full-backup)
      DO_FULL_BACKUP="yes"
      ;;
esac

tar_up (){
   # $1 - level
   # $2 - path
   # $3 - tarball
   EXTRA_ARGS=`echo $@|tr -s [:space:]|cut -d" " -f4-`
   tar -cvjf $REPODIR/$3.$1.tar.bz2 $EXTRA_ARGS --listed-incremental $SNARDIR/$3.snar $2 
   RETVAL=$?
   return $RETVAL
}

run_full_backup(){
   # $1 - path
   # $2 - tarball
   rm -f $SNARDIR/$2.snar
   if [ ! -d $REPODIR/undo ];then
       mkdir -p $REPODIR/undo
   fi
   mv $REPODIR/$2.*.tar.bz2 $REPODIR/undo
   tar_up 0 $1 $2
   if [ "$RETVAL" = "0" ];then
      rm -rf $REPODIR/undo
   fi
}

run_backup (){
   # $1 = disk
   # $2 = image
   if [ ! -d $REPODIR ];then
       mkdir -p $REPODIR
   fi
   if [ ! -d $SNARDIR ];then
       mkdir -p $SNARDIR
   fi

   if [ "$DO_FULL_BACKUP" = "yes" ];then
      run_full_backup $1 $2
   else
      TODAY=`date "+%A"`
      case "$TODAY" in
          Monday)
             run_full_backup $1 $2
             ;;
          Tuesday)
             tar_up 1 $1 $2
             ;;
          Wednesday)
             tar_up 2 $1 $2
             ;;
          Thursday)
             tar_up 3 $1 $2
             ;;
          Friday)
             tar_up 4 $1 $2
             ;;
          Saturday)
             tar_up 5 $1 $2
             ;;
          Sunday)
             tar_up 6 $1 $2
             ;;
       esac
    fi
}


# run_backup <path-to-backup> <tarball-name> <extra-arguments[optional]>
# eg:
# run_backup /var/zope var.zope --exclude=Data.fs\* --exclude=\*.fsz --exclude=\*.dat
